package org.adream.account.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;

/**
 * 文件操作类
 * @author sl
 *
 */
public class FileUtils {
	
	private final static Logger logger = LoggerFactory.getLogger(FileUtils.class);
	
	private FileUtils() {
	}
	
	/**
	 * 文件路径转为byte数组
	 * @param file
	 * @return
	 */
	public static byte[] readFileToByteArray(String file) {
		byte[] data = null;
		try {
			if(!Strings.isNullOrEmpty(file)) {
				data = Files.readAllBytes((new File(file)).toPath());
			}
		} catch (Exception e) {
			if(logger.isInfoEnabled()) {
				logger.info("下载文件出错",e.getMessage());
			}
		}
		return data;
	}
	
	/**
	 * 写文件
	 * @param file
	 * @param is
	 */
	public static void writeToFile(File file,InputStream is) {
		if(is != null && file != null && !file.isDirectory()) {
			try(OutputStream os = new FileOutputStream(file)) {
				byte[] bs = new byte[1024 * 1024];
				int len = 0;
				while((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
					os.flush();
				}
			} catch (Exception e) {
				if(logger.isInfoEnabled()) {
					logger.info("写文件时出错",e);
				}
			}
		}
	}
	
	/**
	 * 删除文件
	 * @param file
	 */
	public static void deleteFile(String file) {
		try {
			File fileTemp = new File(file);
			if(fileTemp.isFile() && fileTemp.exists()) {
				fileTemp.delete();
			}
		} catch (Exception e) {
			if(logger.isInfoEnabled()) {
				logger.info("删除文件时出错",e);
			}
		}
	}
}
